import {Auth} from '@/utils/Auth'
import {Http} from '@/utils/Http'
import {Config} from '@/Config'
import store from "../store";

export const Common = {
	navigateBackRefresh: (num) => {
		num = num ? num + 1 : 2;

		// #ifdef MP-WEIXIN || H5
		var page = getCurrentPages()
		var prePage = page[page.length - num]
		uni.navigateBack()
		return prePage.$vm
		//#endif

		//#ifdef APP-PLUS
		var page = getCurrentPages()
		var prePage = page[page.length - num]
		uni.navigateBack()

		return prePage.$vm
		//#endif
	},

	toUrl(url, isLogin) {
		if (isLogin) {
			if (!Auth.isLogin()) return Auth.toLogin()
		}
		uni.navigateTo({
			url: url
		})
	},
	toTabUrl(url) {
		uni.switchTab({
			url: url
		})
	},
	makePhoneCall(phoneNumber) {
		uni.makePhoneCall({
			phoneNumber: phoneNumber,
			fail(e) {
				console.log(e)
			}
		});
	},

	/**
	 * 对象赋值
	 * @param obj1
	 * @param obj2
	 */
	assign: (obj1, obj2) => {
		const newObj = {}
		for (const key in obj1) {
			if (obj2.hasOwnProperty(key)) {
				newObj[key] = obj2[key]
			} else {
				newObj[key] = obj1[key]
			}
		}

		return newObj
	},

	/**
	 * Object.assign不能复制子素，此方法可解决这个问题
	 * @param obj
	 * @returns {*[]}
	 */
	deepClone: (obj) => {
		let objClone = Array.isArray(obj) ? [] : {};
		if (obj && typeof obj === "object") {
			for (var key in obj) {
				if (obj.hasOwnProperty(key)) {
					//判断ojb子元素是否为对象，如果是，递归复制
					if (obj[key] && typeof obj[key] === "object") {
						objClone[key] = Common.deepClone(obj[key]);
					} else {
						//如果不是，简单复制
						objClone[key] = obj[key];
					}
				}
			}
		}

		return objClone;
	},


	/**
	 * yyyy-M-d h:m:s
	 * @param date
	 * @param type
	 */
	timeFormat: (date, type) => {
		if (typeof date === "string") {
			date = new Date(date)
		}

		let format = 'yyyy-MM-dd hh:mm:ss'

		if (type === 1) {
			format = 'M月d日 hh:m'
		} else if (type === 2) {
			format = 'yyyy-MM-dd'
		} else if (type === 3) {
			format = 'yyyy年M月d日'
		} else if (type === 4) {
			format = 'yyyy-MM'
		} else if (type === 5) {
			format = 'yyyy-MM-dd 00:00:00'
		}

		const o = {
			'M+': date.getMonth() + 1, // month
			'd+': date.getDate(), // day
			'h+': date.getHours(), // hour
			'm+': date.getMinutes(), // minute
			's+': date.getSeconds(), // second11
			'q+': Math.floor((date.getMonth() + 3) / 3), // quarter
			'S+': date.getMilliseconds() // millisecond
		}

		if (/(y+)/.test(format)) {
			format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
		}

		for (const k in o) {
			if (new RegExp('(' + k + ')').test(format)) {
				format = format.replace(
						RegExp.$1,
						RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
				)
			}
		}

		return format
	},
	getWeekDates: () => {
		// 获取当前日期
		var today = new Date();
		// 获取当前是星期几
		var day = today.getDay();
		day = day ? day - 1 : 7; //getDay() 星期日为0，为使周一为0处理

		// 计算本周第一天的日期
		var startDate = Common.addDate(new Date(today.getFullYear(), today.getMonth(), today.getDate() - day),
				1, 4);
		// 计算本周最后一天的日期
		var endDate = Common.addDate(new Date(today.getFullYear(), today.getMonth(), today.getDate() - day + 6),
				1, 4);
		// 返回本周的日期范围
		return {start: startDate, end: endDate};
	},

	plusDate: (date, num, type) => {
		if (typeof date === "string") date = new Date(date)

		//默认添加类型
		if (!type) type = 4

		type = parseInt(type) //类型
		let lIntval = parseInt(num) //间隔

		switch (type) {
			case 6: //年
				date.setYear(date.getYear() + lIntval)
				break;
			case 7: //季度
				date.setMonth(date.getMonth() + (lIntval * 3))
				break;
			case 5: //月
				date.setMonth(date.getMonth() + lIntval)
				break;
			case 4: //天
				date.setDate(date.getDate() + lIntval)
				break
			case 3: //时
				date.setHours(date.getHours() + lIntval)
				break
			case 2: //分
				date.setMinutes(date.getMinutes() + lIntval)
				break
			case 1: //秒
				date.setSeconds(date.getSeconds() + lIntval)
				break;
			default:
		}

		return new Date(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date
				.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds())
	},

	//计算年龄
	calculateAge:(birthday)=> {
		if(!birthday) return 0
		var today = new Date(); // 获取当前日期时间
		var birthdate = new Date(birthday); // 将生日字符串转换为日期格式

		var age = today.getFullYear() - birthdate.getFullYear(); // 根据年份计算年龄

		if (today < birthdate || today.getMonth() < birthdate.getMonth()) {
			age--; // 如果今天的月份小于生日的月份或者今天的日期小于生日的日期，则年龄需要减1
		}

		return age;
	},

	jsonSort: (json, key) => {
		for (let j = 1; j < json.length; j++) {
			let temp = json[j],
					val = temp[key],
					i = j - 1;
			while (i >= 0 && json[i][key] > val) {
				json[i + 1] = json[i];
				i = i - 1;
			}
			json[i + 1] = temp;

		}
		return json;
	},

	getChildrenListByParentId: (parentId, region) => {
		if (!region) return [];
		for (var i = 0; i < region.length; i++) {
			let item = region[i]
			if (item.value === parentId) {
				return item['children']
			}

			let childrenList = Common.getChildrenListByParentId(parentId, item['children'])
			if (childrenList.length > 0) {
				return childrenList
			}
		}

		return []
	},
	showEditor(content){
		if(!content) return ''
		return content.replace(RegExp("<img", "g"), '<img style="max-width:100%;height:auto;display:block;"')
	},
	batchUploadFile(imgArr, i, callback) {
		if(!imgArr || imgArr.length === 0) return callback([])
		Http.uploadFile({filePath: imgArr[i]}).then((url) => {
			imgArr[i] = url
			if (i < imgArr.length - 1) {
				i++
				return Common.batchUploadFile(imgArr, i, callback)
			} else {
				callback(imgArr)
			}
		})
	},
	regexHtmlImg(html) {
		let imgArr = []
		let regex = new RegExp(/<img.*?(?:>|\/>)/gi); // 匹配所有图片
		let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; // 匹配src图片
		let arrsImg = html.match(regex); // obj.info 后台返回的富文本数据
		if (arrsImg != null) {
			for (let a = 0; a < arrsImg.length; a++) {
				let srcs = arrsImg[a].match(srcReg);
				imgArr.push(srcs[1])
			}
		}

		return imgArr
	},

	getRegionName() {
		let regionName = store.state.region.streetShortName
		if (!regionName) {
			regionName = store.state.region.cityShortName
		}

		return regionName
	},

	// 两点间距离lat1,  lng1,  lat2,  lng2
	calcMapDistance(lng,lat){

		var lng1 = lng
		var lat1 = lat

		var lng2 = store.state.region.lng
		var lat2 = store.state.region.lat

		if(!lng1||!lat1||!lng2||!lat2){
			return '0km'
		}

		var radLat1 = lat1*Math.PI / 180.0;
		var radLat2 = lat2*Math.PI / 180.0;
		var a = radLat1 - radLat2;
		var  b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
				Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
		s = s *6378.137 ;// EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;

		s = s * 1000

		if (isNaN(s)) {
			return 0+'m';
		}

		if (s > 1000) {
			//    大于1000米时
			s = Math.floor(s/1000 * 100) / 100;
			s = s.toFixed(2) + 'km'
		} else {
			//    小于1000米直接返回
			s = s.toFixed(2) + 'm'
		}

		return s;
	},
	openLocation(lng,lat,name,address){
		uni.openLocation({
			longitude: parseFloat(lng),
			latitude: parseFloat(lat),
			name:name,
			address:address,
			success: function () {
				console.log('success');
			},
			fail(e){
				console.log(e)
			}
		});
	},
	showGoodsPrice: (data) => {
		let userInfo = uni.getStorageSync('UserInfo')

		if (userInfo.isSeller && data.goodsVipPrice) {
			data.goodsPrice = data.goodsVipPrice
		}

		if (data.goodsPrice) {
			data.goodsPrice = data.goodsPrice / 100
		}

		if (data.totalMoney) {
			data.totalMoney = data.totalMoney / 100
		}

		return data
	},
	isWechat: function() {
		var ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			return true;
		} else {
			return false;
		}
	},
}
